//
//  ALStausAccountViewModel.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/13.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
import SDWebImage

class ALStausAccountViewModel: NSObject {

    
    // 单例
    static let sharedInstance: ALStausAccountViewModel = ALStausAccountViewModel()
    
    /// 加载本地数据
    private func loadLocalStatuses() {
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        
        // 函数抛出异常在函数后面有 throws,表示这段有可能会出现异常, 如果我们处理这个异常,程序是不会挂掉的,不处理就会挂掉
        // try!: 强制try, 有异常不处理,如果真的出现异常程序就挂了
        // do try catch: 处理异常,如果出现异常会走catch这个代码块,程序不会挂掉
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
            ALPrint("json: \(json)")
        } catch let error as NSError {
            ALPrint("json序列化异常: \(error)")
        }
    }

    
    /// 加载微博数据
    /// since_id: 下拉刷新获取最新微薄
    /// max_id: 上拉加载老的数据
    
    func loadStatus(since_id: Int64, max_id: Int64, loadCallBack:(statuses:[ALStatus]?,error:NSError?)->()) {
        // 1.urlString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 2.参数
        var parameters:[String:AnyObject] = ["access_token": ALUserAccountViewModel.userAccountViewModel.userAccount!.access_token!]
        // 将since_id, max_id拼接到请求参数里面
        if since_id > 0 {   // 别人转了since_id
            parameters["since_id"] = NSNumber(longLong: since_id)
        } else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id)
        }
        
        let debug = false
        if debug {
            // 加载数据
            loadLocalStatuses()
            return
        }

        
        ALNetWorkTool.shareInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
//            ALPrint("获取微博数据成功了: \(responseObject)")
            
            //获取微博数据
            if let dict = responseObject as? [String:AnyObject],let statusesDict = dict["statuses"] as? [[String:AnyObject]]{
//            定义数组来保存转好的微博模型
                var statusModels:[ALStatus] = []
                
//                便利每个字典
                for dict in statusesDict{
//                字典转模型
                    let status = ALStatus(dict:dict)
//                    将模型添加到数组中
                    statusModels.append(status)
                }
                
                //缓存图片
                self.cacheWebImage(statusModels, loadCallBack: loadCallBack)
//                数据加载车功能工回调
//                loadCallBack(statuses : statusModels ,error : nil)
            }
            // 缓存图片
        }) { (task, error) -> Void in
            ALPrint("获取微博数据失败了: \(error)")
            loadCallBack(statuses: nil ,  error: error)
        }
    }
    //图片缓存
    private func cacheWebImage(statuses:[ALStatus],loadCallBack:(statuses:[ALStatus]?,error:NSError?)->()){
    
        //创建数组
        let group = dispatch_group_create()

        //判断每个模型,看看是不是有图片要下载
        for status in statuses{
            var downloadURLs:[NSURL]?
            
            downloadURLs = status.storePicutreURLs
            
            //如果没有原创图片下载,看被转发微博是不是有图片下载
            if downloadURLs == nil{
                //将转发微博的图片数组赋值给图片数组
              downloadURLs = status.retweeted_status?.storePicutreURLs
            }
            if let urls = downloadURLs {
                //只有一张图片的时候才在tableview展示出来之前去下载,其他的等到tableview展示出来以后再去下载这样可以提高微博的加载速度
                if urls.count==1 {
                    
                    //获取一张要下载的图片
                    let url = urls.first
                    //进入组
                    // 使用SDWebImage去下载图片
                    // options: [SDWebImageOptions.AvoidAutoSetImage, SDWebImageOptions.CacheMemoryOnly]
                    
                    dispatch_group_enter(group)

                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) in
//                        异步下载图片完成以后就回调用这个闭包
                        dispatch_group_leave(group)
                        if error != nil{
                        ALPrint("图片下载失败")
                            return
                        }
//                        ALPrint("单张图片下载完成")
                    })
                }
            }
        }
        
        //监听所有微博数据下载完成----只有是单张图片的时候才等到下载完成以后区更新UI
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            // SD下载所有图片完成,回调控制器,控制器会拿到数据,然后刷新界面
            ALPrint("图片下载完成")
            loadCallBack(statuses: statuses, error: nil)
            
        }
    }
//发微博请求
    func sendStatus(text:String,image:UIImage?, sendStatusCallback:(error:NSError?) ->()){
        //首先要能保证获取到accessToken,用守卫进行保证,当获取不到的时候返回一个错误,其中返回错误的内容
        guard let access_token = ALUserAccountViewModel.userAccountViewModel.userAccount?.access_token else{
        
            print("access_token为空")
            
            //定义错误
            let error = ALNetworkError.accessTokenEmpty.error()
            //回掉发送错误消息
            
            sendStatusCallback(error: error)
            return
        }
        

        
        //参数
        let parameters = [
        
            "access_token":access_token,
            "status":text
        ]
        
        if image == nil {
            //url
            let url = "https://api.weibo.com/2/statuses/update.json"
            //请求
            ALNetWorkTool.shareInstance.POST(url, parameters: parameters, progress: nil, success: { (task, responseObject) in
                print("\(responseObject)")
                //成功回调
                sendStatusCallback(error: nil)
            }) { (task, error) in
                //错误回掉
                sendStatusCallback(error: error)
            }
        }else{
            let url = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            //请求
           ALNetWorkTool.shareInstance.POST(url, parameters: parameters, constructingBodyWithBlock: { (formdata) in
            //要发布的是图片的二进制数
            let data = UIImagePNGRepresentation(image!)
            formdata.appendPartWithFileData(data!, name: "pic", fileName: "", mimeType: "image/png")
            }, success: { (_, responseObject) in
                sendStatusCallback(error: nil)
            }, failure: { (_, error) in
                sendStatusCallback(error: error)
                print("\(error)")
           })
        }
    }
}
